package api

import (
	"gitee.com/ChangPaoZhe/devops/apps/cmdb"
	"gitee.com/ChangPaoZhe/devops/apps/cmdb/impl"
	"gitee.com/ChangPaoZhe/devops/httpresponse"
	"github.com/gin-gonic/gin"
) 



func  NewDefaultRegisterRequest()  *cmdb.RegisterRequest {
	return  &cmdb.RegisterRequest{
		Resource: &cmdb.Resource{},
	}
}


func (c *CmdbHttp) Search(r *gin.Context)  {
	req:=impl.NewDefaultSearchRequest()
	if err:=r.BindJSON(req);err!=nil {
		httpresponse.Failed(r,httpresponse.NewParamError("参数传递错误：%s",err))
		return 
	}
	ins,err:=c.svc.Search(r.Request.Context(), req)
	if err!=nil {
		httpresponse.Failed(r,httpresponse.NewAuthFailed("CMDB 返回错误：%s",err))
		return 
	}
	var start,end  int64 
	if req.PackageNum!=0 && req.PackageSize!=0 {
		start=(req.PackageNum-1)*req.PackageSize
		end=req.PackageNum*req.PackageSize
		if end > ins.Totalcount{
			end=ins.Totalcount
		}
		if start > ins.Totalcount {
			start=0
		}
	}else {	
		start=0
		end=ins.Totalcount-1 
	}
	httpresponse.Success(r, cmdb.SearchReponseResource{
		Totalcount: end-start,
		Values: ins.Values[start:end],
	})
}


func (c *CmdbHttp) Register(r *gin.Context){
	req:=NewDefaultRegisterRequest()

	if err:=r.BindJSON(req);err!=nil {
		httpresponse.Failed(r,httpresponse.NewParamError("参数传递错误：%s",err))
		return 
	}
	ins,err:=c.svc.Register(r.Request.Context(), req)
	if err!=nil {
		httpresponse.Failed(r,httpresponse.NewAuthFailed("CMDB 返回错误：%s",err))
		return 
	}
	httpresponse.Success(r, ins)
}
